import {
  // ArrowDownOutlined,
  // ArrowUpOutlined,
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import { ProTable } from "@ant-design/pro-components";
// import type { DataType } from "@antv/l7";
// import type { TableProps } from "antd";
import { Button, Modal, message, Switch } from "antd";

import { useEffect, useRef, useState } from "react";
import PopconfirmButton from "@/components/PopconfirmButton";
import { useStatusDictsModel } from "@/models/dicts";
import {
  changeUserStatus,
  deleteUser,
  deptTree,
  resetUserPwd,
  userList,
} from "@/services/ant-design-pro/api";
// import { download } from "@/utils/donwload";
import AddUserModle from "./AddUserModle";
import ImportModle from "./ImportModle";
import { UserResetForm } from "./ResetPasswordModle";
import { useAccess } from "@/hooks/access";

// const {} = DatePicker;

// 获取所有节点 key（递归）
// const getAllKeys: any = (nodes: any[]): string[] => {
//   const keys: string[] = [];
//   nodes.forEach((n) => {
//     keys.push(n.id);
//     if (n.children) keys.push(...getAllKeys(n.children));
//   });
//   return keys;
// };
let defaultTreeData: TreeDataNode[] = [];
const App = () => {
  const myTableRef = useRef<any>(null);
  const [importOpen, setImportOpen] = useState<boolean>(false);
  const [resetPasswordOpen, setResetPasswordOpen] = useState<boolean>(false);
  const [updateKey, setUpdateKey] = useState<number>(0);
  const [userId, setUserId] = useState<number>();
  const { permissions } = useAccess();
  const canAddUser = permissions.includes("system:user:add");
  //system:user:resetPwd
  const canResetUser = permissions.includes("system:user:resetPwd");
  const canEditUser = permissions.includes("system:user:edit");
  //system:user:remove
  const canRemoveUser = permissions.includes("system:user:remove");
  //system:user:import
  const canImportUser = permissions.includes("system:user:import");
  //system:user:query
  const canQueryUser = permissions.includes("system:user:query");
  //system:user:export
  const canExportUser = permissions.includes("system:user:export");
  //system:user:list
  const canListUser = permissions.includes("system:user:list");
  // const [updateing, setUpdating] = useState<boolean>(false);
  // const [form] = Form.useForm();
  const [userName, setUserName] = useState<string>("");
  // const [dataSource, setDataSource] = useState<API.UserListItem[]>([]);
  //导出loading
  // const [exportLoading, setExportLoading] = useState<boolean>(false);

  const resetFormRef = useRef<any>(null);
  const [pageNum] = useState<number>(1);
  const [pageSize] = useState<number>(10);
  // const [loading, setLoading] = useState<boolean>(false);
  // const [deptId, setDeptId] = useState<number>();
  // const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  // const [searchValue, setSearchValue] = useState("");
  // const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  const [addOpen, setAddOpen] = useState<boolean>(false);
  // const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { statusOptions } = useStatusDictsModel();

  const columns = [
    // {
    //   title: "用户编号",
    //   dataIndex: "userId",
    //   key: "userId",
    //   search: false,
    // },
    {
      title: "员工代码",
      dataIndex: "userName",
      key: "userName",
      width: "15%",
    },
    {
      title: "员工姓名",
      dataIndex: "nickName",
      key: "nickName",
      width: "15%",
    },
    //部门
    // {
    //   title: "部门名称",
    //   dataIndex: "deptName",
    //   key: "deptName",
    //   search: false,
    //   render: (_: any, record: API.UserListItem) => {
    //     return record.dept ? record.dept.deptName : "";
    //   },
    // },
    //手机号
    {
      title: "手机号码",
      dataIndex: "phonenumber",
      key: "phonenumber",
      width: "15%",
    },
    //roles
    {
      title: "角色",
      dataIndex: "roles",
      key: "roles",
      search: false,
      width: "15%",
      render: (_: any, _record: API.UserListItem) => {
        const [role] = _ || [];
        return role?.roleName || "--";
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      valueType: "select",
      search: false,
      width: "15%",
      valueEnum: statusOptions.reduce((prev, curr) => {
        prev[curr.value] = { text: curr.label };
        return prev;
      }, {} as Record<string, { text: string }>),
      // render <Switch /> 组件
      render: (_: any, record: API.UserListItem) => {
        if (!canEditUser) {
          return statusOptions.find((item) => item.value === record.status)
            ?.label;
        }
        // switch
        return (
          <Switch
            key={updateKey}
            disabled={record.admin}
            defaultChecked={record.status === "0"}
            unCheckedChildren="停用"
            checkedChildren="正常"
            onChange={async (checked) => {
              const { success, msg } = await changeUserStatus({
                status: checked ? "0" : "1",
                userId: record.userId,
              });
              if (success) {
                message.success("状态修改成功");
              } else {
                message.error(msg || "状态修改失败");
              }
            }}
          />
        );
      },
    },
    // {
    //   title: "创建时间",
    //   dataIndex: "createTime",
    //   key: "createTime",
    //   // hideInTable: true,
    //   valueType: "dateRange",
    //   render: (_: any, record: API.UserListItem) => {
    //     return record.createTime;
    //   },
    // },
    // 操作
    {
      title: "操作",
      key: "action",
      search: false,
      width: 260,
      render: (_: any, record: API.UserListItem) => [
        canEditUser ? (
          <Button
            key={"edit"}
            type="link"
            size="small"
            icon={<EditOutlined />}
            disabled={record.admin}
            onClick={() => {
              setUserId(record.userId);
              setAddOpen(true);
            }}
          >
            编辑
          </Button>
        ) : null,
        canRemoveUser ? (
          <PopconfirmButton
            key={"del"}
            size="small"
            title={`确定删除 " ${record.nickName} " 吗？`}
            type="link"
            danger={false}
            icon={<DeleteOutlined />}
            disabled={record.admin}
            onConfirm={() => {
              delItems(record.userId?.toString());
            }}
          >
            删除
          </PopconfirmButton>
        ) : null,
        canResetUser ? (
          <Button
            key={"reset"}
            size="small"
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setUserId(record.userId);
              setResetPasswordOpen(true);
              setUserName(record.userName);
            }}
            disabled={record.admin}
          >
            重置密码
          </Button>
        ) : null,
        // <TableDropdown
        //   key="actionGroup"
        //   // onSelect={() => action?.reload()}
        //   menus={[
        //     {
        //       key: "resetpassword",
        //       name: "重置密码",
        //       disabled: record.admin,
        //       onClick: () => {
        //         setUserId(record.userId);
        //         setResetPasswordOpen(true);
        //         setUserName(record.userName);
        //       },
        //     },
        //     {
        //       key: "config",
        //       name: "分配用户",
        //       disabled: record.admin,
        //       onClick: () => {
        //         //
        //         history.push(`/system/role/auth/${record.userId}`);
        //       },
        //     },
        //   ]}
        // />,
      ],
    },
  ];
  // const expandAll = () => {
  //   // setExportLoading(true);
  //   const values = form.getFieldsValue();
  //   // const { createTime } = values;
  //   // let [beginTime, endTime] = createTime || [];
  //   download(
  //     "/api/system/user/export",
  //     { pageNum, pageSize, deptId, ...values },
  //     `user_${Date.now()}.xlsx`
  //   );
  //   setTimeout(() => {
  //     setExportLoading(false);
  //   }, 3000);
  // };
  const fetchTree = async () => {
    const { data = [] } = await deptTree();
    // const [first = {}] = data as any[];
    // setTreeData(data);
    try {
      defaultTreeData = JSON.parse(JSON.stringify(data));
    } catch (error) {
      console.log("deep copy error:", error);
    }
    console.log(defaultTreeData);
    // setExpandedKeys(getAllKeys(data));
    // setDeptId(first?.id);
  };
  // const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  //   const { value } = e.target;
  //   setSearchValue(value);
  //   if (!value) {
  //     console.log(defaultTreeData);
  //     setTreeData(defaultTreeData);
  //     setExpandedKeys(getAllKeys(defaultTreeData));
  //     return;
  //   }
  //   const filterTree = (nodes: any[]): any[] => {
  //     const filteredNodes: any[] = [];
  //     nodes.forEach((n) => {
  //       if (n.label.includes(value)) {
  //         filteredNodes.push(n);
  //       } else if (n.children) {
  //         const filteredChildren = filterTree(n.children);
  //         if (filteredChildren.length > 0) {
  //           filteredNodes.push({ ...n, children: filteredChildren });
  //         }
  //       }
  //     });
  //     return filteredNodes;
  //   };
  //   const filteredData = filterTree(defaultTreeData);
  //   setTreeData(filteredData);
  //   setExpandedKeys(getAllKeys(filteredData));
  // };
  // const onSelect = (selectedKeys: React.Key[]) => {
  //   setDeptId(selectedKeys[0] as never);
  // };

  const reload = () => {
    myTableRef.current?.reload();
  };

  const delItems = async (keys: string) => {
    const res = await deleteUser(keys);
    const { code, msg } = res;
    if (code === 200) {
      message.success("删除成功");
      // 清空选择项
      // setSelectedRowKeys([]);
      reload();
    } else {
      console.log("删除失败", msg);
      message.error(msg);
    }
  };
  // const editItem = () => {
  //   setUserId(selectedRowKeys[0] as number);
  //   setAddOpen(true);
  // };
  // add

  useEffect(() => {
    fetchTree();
  }, []);

  // rowSelection object indicates the need for row selection
  // const rowSelection: TableProps<DataType>["rowSelection"] = {
  //   onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
  //     console.log(
  //       `selectedRowKeys: ${selectedRowKeys}`,
  //       "selectedRows: ",
  //       selectedRows
  //     );
  //     setSelectedRowKeys(selectedRowKeys);
  //   },
  //   getCheckboxProps: (record: any) => ({
  //     disabled: record.admin, // Column configuration not to be checked
  //   }),
  // };
  const resetPassword = async () => {
    await resetFormRef.current.validate();
    const values = resetFormRef.current.getValues();
    const { code, msg } = await resetUserPwd({
      userId,
      password: values.newPassword,
    });
    if (code === 200) {
      message.success("重置密码成功");
      setResetPasswordOpen(false);
    } else {
      message.error(msg);
    }
  };
  return (
    <div>
      {/* <Row gutter={[gutter, gutter]} wrap={false}>
          <Col flex={"220px"}>
            <Row gutter={[gutter, gutter]}>
              <Col span={24}>
                <Search
                  value={searchValue}
                  onChange={onChange}
                  placeholder="请输入部门名称"
                />
              </Col>
              <Col span={24}>
                {treeData.length === 0 && <Empty description="暂无数据" />}

                <Tree
                  // autoExpandParent={true}
                  fieldNames={{
                    title: "label",
                    key: "id",
                  }}
                  selectedKeys={deptId !== undefined ? [deptId] : []}
                  // loadData={async () => {
                  //   const { data } = await deptTree();
                  //   return data;
                  // }}
                  // checkable
                  // defaultSelectedKeys={["0-1"]}
                  defaultExpandAll
                  expandedKeys={expandedKeys}
                  treeData={treeData}
                  blockNode
                  onExpand={(expandedKeys) => {
                    setExpandedKeys(expandedKeys);
                  }}
                  onSelect={onSelect}
                />
              </Col>
            </Row>
          </Col> */}
      {/* <Col flex={"auto"}> */}
      <ProTable
        actionRef={myTableRef}
        rowKey={"userId"}
        //去掉最后一个操作列
        columns={
          canEditUser || canRemoveUser || canResetUser
            ? columns
            : columns.slice(0, -1)
        }
        search={{
          span: 6,
          labelWidth: "auto",
          defaultCollapsed: false,
        }}
        // params={{ deptId }}
        // rowSelection={{
        //   type: "checkbox",
        //   ...rowSelection,
        // }}
        toolBarRender={() => [
          canAddUser ? (
            <Button
              ghost
              key={"xz"}
              type="primary"
              size="small"
              icon={<PlusOutlined />}
              onClick={() => {
                setAddOpen(true);
              }}
            >
              新增
            </Button>
          ) : null,
          // <Button
          //   key={"bj"}
          //   type="primary"
          //   ghost
          //   icon={<EditOutlined />}
          //   disabled={selectedRowKeys.length !== 1}
          //   onClick={editItem}
          // >
          //   编辑
          // </Button>,
          // <PopconfirmButton
          //   key={"xc"}
          //   icon={<DeleteOutlined />}
          //   disabled={selectedRowKeys.length === 0}
          //   title="确定删除吗？"
          //   onConfirm={() => {
          //     delItems(selectedRowKeys?.join(","));
          //   }}
          // >
          //   删除
          // </PopconfirmButton>,
          // <Button
          //   key={'daoru'}
          //   onClick={() => {
          //     setImportOpen(true);
          //   }}
          //   type="dashed"
          //   icon={<ArrowUpOutlined />}
          // >
          //   导入
          // </Button>,
          // <Button
          //   key={'daochu'}
          //   disabled={exportLoading}
          //   icon={<ArrowDownOutlined />}
          //   onClick={expandAll}
          //   type="dashed"
          // >
          //   导出
          // </Button>,
        ]}
        scroll={{
          x: 900,
        }}
        request={async (params) => {
          const { createTime, deptId, ...rests } = params as any;
          const [beginTime, endTime] = createTime || [];
          setUserId(undefined);
          const query = {
            pageNum,
            pageSize,
            deptId,
            ...rests,
            // params,
            "params[beginTime]": beginTime,
            "params[endTime]": endTime,
          };
          //删除undefined的key
          Object.keys(query)?.forEach((key) => {
            query[key] === undefined && delete query[key];
          });
          const { code, rows, total } = await userList(query);
          setTimeout(() => {
            setUpdateKey(Math.random());
          }, 100);
          return { data: rows, total, success: code === 200 };
        }}
      />
      {/* </Col> */}
      {/* </Row> */}

      {resetPasswordOpen && userId ? (
        <Modal
          title="重置密码"
          open={true}
          onCancel={() => {
            setResetPasswordOpen(false);
          }}
          onOk={resetPassword}
        >
          <UserResetForm
            userId={userId}
            userName={userName}
            ref={resetFormRef}
          />
        </Modal>
      ) : null}
      {importOpen ? (
        <ImportModle
          closed={() => {
            setImportOpen(false);
          }}
        />
      ) : null}

      {addOpen ? (
        <AddUserModle
          userId={userId}
          onClose={(reflash) => {
            setUserId(undefined);
            setAddOpen(false);
            if (reflash) {
              reload();
            }
          }}
        />
      ) : null}
    </div>
  );
};
export default App;
